import Vue from 'vue'
import Vuex from 'vuex'
import axios from '@/store/ajax.js'
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		url: {
			upload: "https://bpapi.jinghushi.com/order.php/util/upload",
		},
		version: '',
		Location: {
			x: '',
			y: ''
		},
		city: '',
		address: '',
		level: {},
		// 直播相关 开始
		ws: null, // socket 对象
		wsUrl: 'ws://47.93.43.172:8282', // 地址
		reconnectNum: 3, // 重连最大次数
		socketState: 'init', // socket 状态 默认初始化 init:初始化 wait:等待响应  connect:连接 close:关闭
		aliveInterval: null, // 心跳定时器
		sendQueue: [], // 发送队列
		room_no: '',
		count: '',
		chatList: [],
		userInfo: uni.getStorageSync('userInfo') || {},
		_$cartList: [],
		live_pull_url: '',
		anchor:{},
		// 直播相关 结束
	},
	mutations: {
		// 直播相关 开始
		setCartList(state) {
		
		},
		setRoomNo(state, val) {
			state.room_no = val.id
			state.live_pull_url = val.live_pull_url
			state.anchor = val.anchor
			
		},
		sendWebSocket(state, data) {
			if (state.ws && state.socketState === 'connect') {
				uni.sendSocketMessage({
					data: JSON.stringify(data),
					success: () => {
						// if (data.type == 'say') {
						// 	state.chatList.push(data.data)
						// 	console.log('消息发送成功', state.chatList);
						// 	uni.$emit('chatListEvent', state.chatList)
						// }
					},
					fail: (err) => {
						console.error('消息发送失败:', err);
					}
				});
			} else {
				console.error('WebSocket 未连接或连接已关闭，无法发送消息');
			}
		},
		initSocket(state) {
			state.socketState = 'wait';
			state.ws = uni.connectSocket({
				url: state.wsUrl,
				success: () => {
					uni.showToast({
						title: '创建成功时',
						icon: 'success',
						duration: 2000
					});
					state.socketState = 'connect';
					store.commit('keepAlive', state);
					store.commit('getMid');
				},
				fail: (err) => {
					console.error('WebSocket 连接失败:', err);
				}
			});
		
			uni.onSocketOpen(() => {
				console.log('WebSocket 连接已打开');
			});
		
			uni.onSocketMessage((res) => {
				const data = JSON.parse(res.data);
				console.log('收到消息:', data)
				if (data.type == 'online_update') {
					state.count = data.count
					uni.$emit('count', state.count)
		
				}else if (data.type == 'say') {
					state.chatList.push(data.data)
					console.log('消息发送成功', state.chatList);
					uni.$emit('chatListEvent', state.chatList)
				}
			});
		
			uni.onSocketClose((e) => {
				state.socketState = 'close';
				console.log("close", e);
				console.log("WebSocket 连接关闭");
				if (state.aliveInterval) {
					clearInterval(state.aliveInterval);
					state.aliveInterval = null;
				}
				if (e.code === 1000) {
					if (state.reconnectNum) {
						state.reconnectNum--;
						setTimeout(() => {
							store.commit('initSocket');
						}, 60000);
					}
				} else {
					console.error("WebSocket 异常连接关闭，停止连接");
				}
			});
		
			uni.onSocketError((e) => {
				console.log('WebSocket 连接错误:', e);
			});
		},
		keepAlive(state) {
			// 定时发送心跳包
			state.aliveInterval = setInterval(() => {
				let data = {
					type: "ping"
				};
				uni.sendSocketMessage({
					data: JSON.stringify(data),
					success: () => {
						// console.log('心跳包发送成功');
					},
					fail: (err) => {
						// console.error('心跳包发送失败:', err);
					}
				});
			}, 30000);
		},
		
		getMid(state) {
			axios('Center/main', "POST", 'member').then(res => {
				if (res.data.code == 200) {
					state.mid=res.data.data.mid
					let data = {
						"type": "login",
						"data": {
							"user_id": res.data.data.member.id,
							"room_no": state.room_no
						}
		
					}
					console.log(data);
					//
					store.commit('sendWebSocket', data);
				}
			})
		},
		// 直播相关 结束
		upversion(state, info) {
			state.version = info
		},
		upLocation(state, info) {
			// 变更状�
			state.Location = {
				...info
			}
		},
		upcity(state, info) {
			state.city = info
		},
		upaddress(state, info) {
			state.address = info
		},
		uplevel(state, info) {
			state.level = info
		},
	},
	actions: {

	}
})

export default store